package wcs

import (
	"errors"
	"fmt"
	"gitee.com/wcs2/common/models"
	"gorm.io/gorm"
	"time"
)

// 设备类型结构体
type BizDeviceType struct {
	models.BaseModel
	TypeName string      `gorm:"not null;column:type_name;type:varchar(160);" json:"typeName"` //comment:设备类型名称
	TypeCode string      `gorm:"type:varchar(60);column:type_code;unique" json:"typeCode"`     //comment:设备类型编码
	State    string      `gorm:"not null;type:varchar(60);column:state" json:"state"`          //comment:当前状态
	ExtData  models.JSON `gorm:"type:json;column:ext_data" json:"extData"`                     //comment:扩展信息
	Devices  []BizDevice `gorm:"foreignKey:TypeId;" json:"devices"`                            //comment:关联设备
}

func (bizDeviceType *BizDeviceType) BeforeCreate(tx *gorm.DB) (err error) {
	crtime := models.Time{
		time.Now(),
	}
	var deviceType BizDeviceType

	if !errors.Is(tx.Where("type_code =?", bizDeviceType.TypeCode).First(&deviceType).Error, gorm.ErrRecordNotFound) {
		return errors.New(fmt.Sprintf("己存在%s的设备类型编码。", bizDeviceType.TypeCode))
	}

	bizDeviceType.Crtime = crtime
	return
}

func (bizDeviceType *BizDeviceType) BeforeUpdate(tx *gorm.DB) (err error) {
	modtime := models.Time{
		time.Now(),
	}
	var deviceType BizDeviceType

	if !errors.Is(tx.Where("type_code =? and id <> ?", bizDeviceType.TypeCode, bizDeviceType.ID).First(&deviceType).Error, gorm.ErrRecordNotFound) {
		return errors.New(fmt.Sprintf("己存在%s的设备类型编码。", bizDeviceType.TypeCode))
	}

	bizDeviceType.Modtime = modtime
	return
}

func (bizDeviceType *BizDeviceType) TableName() string {
	return "biz_device_type"
}

//设备信息表
type BizDevice struct {
	models.BaseModel
	TypeId      uint64  `gorm:"column:type_id" json:"typeId"`                                 //comment:设备类型
	TypeName    string  `gorm:"column:type_name" json:"typeName"`                             //comment:设备类型名称
	DeviceCode  string  `gorm:"column:device_code;type:varchar(60);unique" json:"deviceCode"` //comment:设备编码
	DeviceName  string  `gorm:"column:device_name;type:varchar(60);" json:"deviceName"`       //comment:设备名称
	State       string  `gorm:"not null;type:varchar(60);column:state" json:"state"`          //comment:当前状态
	AreaCode    string  `gorm:"column:area_code;type:varchar(60);" json:"areaCode"`           //comment:所属区域
	RelatedCode string  `gorm:"column:related_code;type:varchar(60);" json:"relatedCode"`     //comment:关联编码(打印机可能会用到)
	Voltage     float32 `gorm:"column:voltage;" json:"voltage"`                               //comment:设备电量
	ProjectId   uint64  `gorm:"column:project_id" json:"projectId"`                           //comment:项目编号
	ProjectName string  `gorm:"column:project_name;type:varchar(160);" json:"projectName"`    //comment:项目名称
}

func (bizDevice *BizDevice) TableName() string {
	return "biz_device"
}

func (bizDevice *BizDevice) AfterUpdate(tx *gorm.DB) (err error) {
	if bizDevice.ID != 0 {
		tx.Model(&BizDevice{}).Where("id = ?", bizDevice.ID).Update("modtime", time.Now())
	}

	return
}
